package com.guyaogg.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.utils.HttpUtils;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.gulimall.member.dao.MemberDao;
import com.guyaogg.gulimall.member.dao.MemberLevelDao;
import com.guyaogg.gulimall.member.entity.MemberEntity;
import com.guyaogg.gulimall.member.entity.MemberLevelEntity;
import com.guyaogg.gulimall.member.execption.EmailExistException;
import com.guyaogg.gulimall.member.execption.PhoneExistException;
import com.guyaogg.gulimall.member.execption.UsernameExistException;
import com.guyaogg.gulimall.member.service.MemberService;
import com.guyaogg.gulimall.member.vo.GiteeSocialUser;
import com.guyaogg.gulimall.member.vo.GiteeTokenVO;
import com.guyaogg.gulimall.member.vo.MemberLoginVO;
import com.guyaogg.gulimall.member.vo.MemberRegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    private final MemberLevelDao memberLevelDao;

    public MemberServiceImpl(MemberLevelDao memberLevelDao) {
        this.memberLevelDao = memberLevelDao;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegisterVO vo) {
        // 先检查 用户名和电话 数据唯一 ,利用异常机制让上层感知到
        checkUsernameUnique(vo.getUsername());
        checkMobileUnique(vo.getPhone());

        // 完善保存对象
        MemberEntity memberEntity = new MemberEntity();

        // 设置进 vo 的数据
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());

        log.debug("明文密码为：{}", vo.getPassword());
        // 密码加密存储,Spring 家的盐值加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setNickname(vo.getUsername());

        regDefaultAttr(memberEntity);


        this.baseMapper.insert(memberEntity);
    }

    private void regDefaultAttr(MemberEntity memberEntity) {
        // TODO 其他默认信息

        // 设置默认的会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        log.debug("保存内容：{}", memberEntity);
    }

    @Override
    public void checkEmailUnique(String email) throws EmailExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("email", email));
        if (count > 0) {
            throw new EmailExistException();
        }

    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }

    }

    @Override
    public void checkMobileUnique(String mobile) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", mobile));
        if (count > 0) {
            throw new PhoneExistException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVO vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();

        // 去数据库查询
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct)
                .or().eq("mobile", loginAcct));
        if (entity == null) {
            // 登录失败
            return null;
        } else {
            // 获取到数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity oauth2GiteeLogin(GiteeSocialUser vo) throws Exception {
        // 登录和注册合并逻辑
        // 我先拿数据
        HashMap<String, String> map = new HashMap<>(2);
        map.put("access_token", vo.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);
        if (response.getStatusLine().getStatusCode() == 200) {

            String json = EntityUtils.toString(response.getEntity());
            GiteeTokenVO giteeUser = JSON.parseObject(json, GiteeTokenVO.class);
            String uid = giteeUser.getId().toString();

            // 根据 uid 判断当前用户是否注册过
            MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("gitee_uid", uid));
            if (entity != null) {
                log.debug("gitee 登录");
                MemberEntity update = new MemberEntity();
                update.setGiteeToken(vo.getAccess_token());
                update.setGiteeExpiresIn(vo.getExpires_in().toString());
                update.setId(entity.getId());
                this.baseMapper.updateById(update);
                entity.setGiteeToken(vo.getAccess_token());
                entity.setGiteeExpiresIn(vo.getExpires_in().toString());
                return entity;
            } else {
                log.debug("gitee 注册");
                // 没有查到对应用户进行注册
                MemberEntity reg = new MemberEntity();
                // 设置默认属性，及令牌获取的信息
                reg.setGiteeUid(uid);
                reg.setNickname(giteeUser.getName());
                reg.setGiteeToken(vo.getAccess_token());
                reg.setGiteeExpiresIn(vo.getExpires_in().toString());
                // 等等,默认配置

                this.regDefaultAttr(reg);

                this.baseMapper.insert(reg);
                return reg;


            }
        }else {
            return null;
        }


    }

}